package com.dollama.random.model.impl;

import com.dollama.random.model.RandomModel;
import com.dollama.random.model.entity.Ball;
import com.dollama.random.presenter.RandomPresenter;

import java.util.ArrayList;
import java.util.Random;

/**
 * Created by tony on 2017/5/3.
 */

public class RandomModelImpl implements RandomModel {

    private ArrayList<Ball> fronts,backs,resultFronts,resultBacks;
    private int tempNumber,index;
    private Ball currentBall,tempBall;
    private Random random;
    private String resultStr;

    @Override
    public void createRandomNumber(RandomPresenter randomPresenter) {
        fronts = new ArrayList<>();
        tempNumber = 1;
        for (int a = 0;a<35;a++) {
            currentBall = new Ball();
            currentBall.setNumber(tempNumber);
            fronts.add(currentBall);
            tempNumber++;
        }
        backs = new ArrayList<>();
        tempNumber = 1;
        for (int b = 0;b<12;b++) {
            currentBall = new Ball();
            currentBall.setNumber(tempNumber);
            backs.add(currentBall);
            tempNumber++;
        }
        random = new Random();
        resultFronts = new ArrayList<>();
        for (int c = 0;c<5;c++) {
            index = random.nextInt(fronts.size());
            resultFronts.add(fronts.get(index));
            fronts.remove(index);
        }
        resultBacks = new ArrayList<>();
        for (int d = 0;d<2;d++) {
            index = random.nextInt(backs.size());
            resultBacks.add(backs.get(index));
            backs.remove(index);
        }

        sort(resultFronts);
        sort(resultBacks);

        resultFronts.addAll(resultBacks);

        randomPresenter.showRandom(getString(resultFronts));;
    }

    private void sort (ArrayList<Ball> balls) {
        //对冒泡排序的中间结果做了多余的比较
        for (int e = 0;e<balls.size()-1;e++) {
            for (int f = 0;f<balls.size()-1;f++) {
                if (balls.get(f).getNumber()>balls.get(f+1).getNumber()) {
                    tempBall = balls.get(f+1);
                    balls.set(f+1,balls.get(f));
                    balls.set(f,tempBall);
                }
            }
        }
    }

    private String getString(ArrayList<Ball> balls) {
        resultStr = "";
        for (int g = 0;g<balls.size();g++) {
            if (g!=0) {
                resultStr = resultStr + "-";
            }
            if (balls.get(g).getNumber()<10) {
                resultStr = resultStr + "0" + balls.get(g).getNumber();
            }else {
                resultStr = resultStr + balls.get(g).getNumber();
            }
        }
        return resultStr;
    }

}
